﻿<div id="app">
    <!-- 顶部基础信息区域 -->
    <div class="basic-info" v-if="!loading">
        <!-- 标题与操作按钮 -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3>销售单详情</h3>
            <!-- 操作按钮区域 -->
            <div>
                <!-- 编辑：草稿0/待审核1/已驳回2 -->
                <el-button v-if="['0','1','2'].includes(form.orderStatus)" v-on:click="handleEdit">编辑</el-button>
                <!-- 删除：仅草稿0/待审核1 -->
                <el-button v-if="['0','1'].includes(form.orderStatus)" v-on:click="handleDelete" type="danger">删除</el-button>
                <!-- 审核：仅待审核1 -->
                <el-button v-if="form.orderStatus === '1'" type="primary" v-on:click="openAuditDialog">审核</el-button>
                <!-- 撤销驳回：仅已驳回2 -->
                <el-button v-if="form.orderStatus === '2'" type="warning" v-on:click="handleRejectCancel">撤销驳回</el-button>
                <!-- 关闭订单：仅已审核3 -->
                <el-button v-if="form.isDelete === '0'" type="info" v-on:click="handleCloseOrder">关闭订单</el-button>
                <!-- 启用订单：仅已关闭4 -->
                <el-button v-if="form.isDelete === '1'" type="success" v-on:click="handleEnableOrder">启用订单</el-button>
                <el-button v-on:click="handleCopy">复制</el-button>
                <el-button v-on:click="handlePrint">打印</el-button>
                <!-- 通用按钮：始终显示 -->
                <el-button onclick="window.history.back()">关闭页面</el-button>
            </div>
        </div>

        <!-- 基础信息表单 -->
        <div style="display: flex; flex-wrap: wrap; gap: 15px; margin-top: 10px;">
            <div style="width: 33.33%;">
                <span class="form-label">销售单号：</span>
                <span class="form-value">{{ form.salesOrderNo }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">制单人：</span>
                <span class="form-value">{{ form.createBy }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">所在部门：</span>
                <span class="form-value">{{ form.createShortName }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">制单时间：</span>
                <span class="form-value">{{ form.salesDate }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">单据状态：</span>
                <span class="form-value status-tag" :class="getStatusClass(form.orderStatus)" style="font-weight: bold;">
                    {{ orderStatusText }}
                </span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">审核时间：</span>
                <span class="form-value">{{ formatDate(form.auditorTime) }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">客户名称：</span>
                <span class="form-value">{{ form.customerName }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">联系人：</span>
                <span class="form-value">{{ form.contactPerson }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">联系方式：</span>
                <span class="form-value">{{ form.contactPhone }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">销售部门：</span>
                <span class="form-value">{{ form.sellerShortName }}</span>
            </div>
            <div style="width: 33.33%;">
                <span class="form-label">销售负责人：</span>
                <span class="form-value">{{ form.sellerBy }}</span>
            </div>
            <div style="width: 100%;">
                <span class="form-label">备注：</span>
                <span class="form-value">{{ form.remarks || '无' }}</span>
            </div>
        </div>

        <!-- 总库存/销售金额 -->
        <div style="display: flex; justify-content: center; margin-top: 20px; flex-wrap: wrap;">
            <div class="stats-card">
                <div class="stats-value">{{ form.availableQty || 0 }}</div>
                <div>可用库存</div>
            </div>
            <div class="stats-card">
                <div class="stats-value">¥{{ form.salesAmount || '0.00' }}</div>
                <div>销售金额</div>
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-container" v-if="loading">
        <div style="text-align: center;">
            <div style="font-size: 40px; color: #409eff;">⏳</div>
            <span style="margin-left: 10px;">加载中...</span>
        </div>
    </div>

    <!-- 标签页区域 -->
    <div class="tabs-container" v-if="!loading">
        <el-tabs v-model="activeTab">
            <!-- 其他信息 -->
            <el-tab-pane label="其他信息" name="other">
                <div style="margin-top: 20px;">
                    <h4>附件</h4>
                    <!-- 已上传附件列表 -->
                    <div v-for="(file, index) in uploadedFiles"
                         :key="index"
                         class="file-item"
                         :class="{ 'bg-light': hoverIndex === index }"
                         v-on:mouseenter="hoverIndex = index"
                         v-on:mouseleave="hoverIndex = -1"
                         style="display: flex; align-items: center; margin: 10px 0; padding: 8px; border-radius: 4px; cursor: pointer;">
                        <span style="margin-right: 8px;">📄</span>
                        <span style="flex: 1;">{{ file.name }}</span>
                        <el-button size="small" type="text" style="color: #ff4d4f;" v-on:click="removeFile(index)">删除</el-button>
                    </div>
                    <!-- 上传按钮 -->
                    <el-upload class="upload-demo"
                               action="https://jsonplaceholder.typicode.com/posts/"
                               v-on:success="handleUploadSuccess"
                               v-on:error="handleUploadError"
                               :file-list="fileList"
                               :auto-upload="true"
                               :show-file-list="false"
                               accept=".doc,.docx,.pdf,.rar,.zip"
                               :limit="10"
                               v-on:exceed="handleExceed">
                        <el-button type="primary">上传附件</el-button>
                    </el-upload>
                    <p style="margin: 10px 0; color: #909399;">支持格式：doc、docx、pdf、rar、zip，单文件最大200MB</p>
                </div>
            </el-tab-pane>

            <!-- 商品信息 -->
            <el-tab-pane label="商品信息" name="goods">
                <div style="margin-top: 20px;">
                    <h4>商品信息</h4>
                    <div style="width: 33.33%;">
                        <span class="form-label">商品名称：</span>
                        <span class="form-value">{{ form.goodsNameList }}</span>
                    </div>
                    <div style="width: 33.33%;">
                        <span class="form-label">销售数量：</span>
                        <span class="form-value">{{ form.salesQuantity }}</span>
                    </div>
                    <div style="width: 33.33%;">
                        <span class="form-label">销售金额：</span>
                        <span class="form-value">¥{{ form.salesAmount }}</span>
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="入库记录" name="in">入库记录内容</el-tab-pane>
            <el-tab-pane label="出库记录" name="out">出库记录内容</el-tab-pane>
        </el-tabs>
    </div>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="销售订单审核" width="500px">
        <div style="padding: 20px;">
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: bold;">审核结果</label>
                <el-radio-group v-model="auditResult">
                    <el-radio label="通过" style="margin-right: 20px;">审核通过</el-radio>
                    <el-radio label="驳回">审核驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <label style="display: block; margin-bottom: 8px; font-weight: bold;">审核意见</label>
                <el-input type="textarea"
                          v-model="auditOpinion"
                          rows="4"
                          placeholder="请输入审核意见（可选）"
                          maxlength="200"
                          show-word-limit></el-input>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="auditDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="submitAudit">确定</el-button>
            </div>
        </template>
    </el-dialog>
</div>

<script>
    const { createApp, reactive, ref, onMounted, computed } = Vue;
    const {
        ElMessage, ElTabs, ElTabPane, ElDialog,
        ElTable, ElTableColumn, ElUpload, ElButton, ElMessageBox, ElRadioGroup, ElRadio, ElInput
    } = ElementPlus;

    // 将后端的状态数据传递给前端
    var statusList = @Html.Raw(Json.Serialize(ViewBag.TypeList));
    // 替换原有的 STATUS_CONFIG，使用从后端获取的状态数据
    const STATUS_CONFIG = {};

    const app = createApp({
        setup() {

            // 根据状态值返回对应的样式类
            const getStatusClassByValue = (status) => {
                const classMap = {
                    '0': 'status-draft',
                    '1': 'status-pending',
                    '2': 'status-rejected',
                    '3': 'status-approved',
                    '4': 'status-closed',
                    '5': 'status-approved',
                    '6': 'status-closed'
                };
                return classMap[status] || '';
            };
                    // 从后端获取状态数据
            if (typeof statusList !== 'undefined' && statusList) {
                statusList.forEach(item => {
                    STATUS_CONFIG[item.code] = {
                        text: item.name,
                        class: getStatusClassByValue(item.code) // 根据状态值返回对应的样式类
                    };
                });
            }

            // ---------- 销售单表单数据 ----------
            const form = reactive({
                salesOrderNo: '',
                customerName: '',
                contactPerson: '',
                contactPhone: '',
                sellerBy: '',
                sellerShortName: '',
                salesDate: '',
                orderStatus: '',
                availableQty: 0,
                goodsNameList: '',
                auditorBy: '',
                auditorTime: '',
                auditorComment: '',
                createBy: '',
                createShortName: '',
                createTime: '',
                updateBy: '',
                updateTime: '',
                remarks: '',
                salesQuantity: 0,
                salesAmount: 0,
                salesOrderId: 0
            });

            const orderStatusText = computed(() => {
                return STATUS_CONFIG[form.orderStatus]?.text || '未知状态';
            });

            const getStatusClass = (status) => {
                return STATUS_CONFIG[status]?.class || '';
            };

            // 加载状态
            const loading = ref(true);

            // 从URL获取销售单ID
            const getOrderIdFromUrl = () => {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get('id');
            };

            // 获取销售单详情
            const fetchOrderDetails = async () => {
                try {
                    loading.value = true;
                    const orderId = getOrderIdFromUrl();

                    const response = await axios.post(`/OmSalesOrder/Details?id=${orderId}`);
                    if (response.data.code === 200) {
                        const orderData = response.data.data[0];
                        // 填充表单数据
                        Object.assign(form, orderData);
                        form.salesDate = formatDate(orderData.salesDate);
                        loading.value = false;
                        ElMessage.success('销售单数据加载成功');
                    } else {
                        ElMessage.error('加载销售单详情失败：' + (response.data.msg || '数据异常'));
                        loading.value = false;
                    }
                } catch (error) {
                    console.error('获取销售单详情失败:', error);
                    ElMessage.error('获取销售单信息失败，请刷新页面重试');
                    loading.value = false;
                }
            };

            // 格式化日期
            const formatDate = (dateString) => {
                if (!dateString) return '未知';
                const date = new Date(dateString);
                return date.toLocaleString();
            };

            // ---------- 标签页激活状态 ----------
            const activeTab = ref('other');

            // ---------- 附件上传逻辑 ----------
            const fileList = ref([]);
            const uploadedFiles = ref([
                { name: '销售合同.pdf' },
                { name: '客户签收单.docx' }
            ]);
            const hoverIndex = ref(-1);

            const handleUploadSuccess = (response, file) => {
                uploadedFiles.value.push({
                    name: file.name,
                    url: URL.createObjectURL(file.raw)
                });
                ElMessage.success(`文件 "${file.name}" 上传成功`);
            };

            const handleUploadError = (err, file) => {
                ElMessage.error(`文件 "${file.name}" 上传失败，请重试`);
            };

            const handleExceed = (files) => {
                ElMessage.warning(`最多只能上传10个文件`);
            };

            const removeFile = (index) => {
                uploadedFiles.value.splice(index, 1);
                ElMessage.info(`文件已删除`);
            };

            // ---------- 打印弹窗逻辑 ----------
            const printDialogVisible = ref(false);
            const printData = ref([]);

            const updatePrintData = () => {
                printData.value = [
                    { label: '销售单号', value: form.salesOrderNo },
                    { label: '客户名称', value: form.customerName },
                    { label: '制单时间', value: form.salesDate },
                    { label: '单据状态', value: orderStatusText.value },
                    { label: '销售金额', value: `¥${form.salesAmount}` }
                ];
            };

            const handlePrint = () => {
                updatePrintData();
                printDialogVisible.value = true;
            };

            // ---------- 操作按钮处理 ----------
            const handleEdit = () => {
                ElMessage.info('编辑功能开发中...');
            };

            const handleCopy = () => {
                ElMessage.info('复制销售单功能开发中...');
            };

            // 删除操作
            const handleDelete = async () => {
                try {
                    await ElMessageBox.confirm(
                        '确定要删除这个销售单吗？此操作不可撤销。',
                        '确认删除',
                        { type: 'warning' }
                    );
                    const response = await axios.post(`/OmSalesOrder/Delete/${getOrderIdFromUrl()}`);
                    if (response.data.code === 200) {
                        ElMessage.success('销售单删除成功');
                        setTimeout(() => {
                            window.close();
                            window.opener?.refreshTable(); // 联动管理页刷新
                        }, 1500);
                    }
                } catch (error) {
                    ElMessage.info('已取消删除操作');
                }
            };

            // 撤销驳回操作
            const handleRejectCancel = async () => {
                try {
                    await ElMessageBox.confirm(
                        `确定撤销驳回状态，将销售订单"${form.salesOrderNo}"恢复为「待审核」吗？`,
                        '确认撤销',
                        { type: 'warning' }
                    );
                    // 使用状态变更接口
                    const response = await axios.post(`/OmSalesOrder/AuditorStatus?status=1&id=${getOrderIdFromUrl()}`);
                    if (response.data.success) {
                        form.orderStatus = '1'; // 实时更新状态
                        ElMessage.success('撤销成功！');
                        fetchOrderDetails(); // 刷新数据
                    } else {
                        ElMessage.error('撤销失败');
                    }
                } catch (error) {
                    ElMessage.info('已取消撤销');
                }
            };

            // 关闭订单操作
            const handleCloseOrder = async () => {
                try {
                    await ElMessageBox.confirm(
                        `确定关闭销售订单"${form.salesOrderNo}"吗？`,
                        '确认关闭',
                        { type: 'warning' }
                    );
                    // 使用状态变更接口
                    const response = await axios.post(`/OmSalesOrder/Status?status=1&id=${getOrderIdFromUrl()}`);
                    if (response.data.success) {
                        form.orderStatus = '4'; // 实时更新状态
                        ElMessage.success('销售订单已关闭！');
                        fetchOrderDetails(); // 刷新数据
                    } else {
                        ElMessage.error('关闭失败');
                    }
                } catch (error) {
                    ElMessage.info('已取消关闭');
                }
            };

            // 启用订单操作
            const handleEnableOrder = async () => {
                try {
                    await ElMessageBox.confirm(
                        `确定启用销售订单"${form.salesOrderNo}"吗？`,
                        '确认启用',
                        { type: 'info' }
                    );
                    // 使用状态变更接口
                    const response = await axios.post(`/OmSalesOrder/Status?status=0&id=${getOrderIdFromUrl()}`);
                    if (response.data.success) {
                        form.orderStatus = '3'; // 实时更新状态
                        ElMessage.success('销售订单已启用！');
                        fetchOrderDetails(); // 刷新数据
                    } else {
                        ElMessage.error('启用失败');
                    }
                } catch (error) {
                    ElMessage.info('已取消启用');
                }
            };

            // 审核相关变量和方法
            const auditDialogVisible = ref(false);
            const auditResult = ref('通过');
            const auditOpinion = ref('');

            // 获取当前用户ID - 与管理页保持一致
            const getCurrentUserId = () => {
                const userStr = sessionStorage.getItem('YH');
                if (!userStr) {
                    ElMessage.warning('未检测到登录状态，请重新登录');
                    return '';
                }
                try {
                    const userObj = JSON.parse(userStr);
                    const userId = userObj?.id?.toString() || '';
                    if (!userId) {
                        ElMessage.warning('用户信息不完整，请重新登录');
                    }
                    return userId;
                } catch (error) {
                    console.error('解析用户信息失败：', error);
                    ElMessage.error('用户信息异常，请重新登录');
                    return '';
                }
            };

            // 打开审核对话框
            const openAuditDialog = () => {
                if (form.orderStatus !== '1') {
                    ElMessage.warning('只有「待审核」状态的订单可以审核');
                    return;
                }
                auditResult.value = '通过';
                auditOpinion.value = '';
                auditDialogVisible.value = true;
            };

            // 提交审核 - 使用与管理页相同的参数格式
            const submitAudit = async () => {
                const newStatus = auditResult.value === '通过' ? '3' : '2';
                const usersId = getCurrentUserId();

                try {
                    const response = await axios.post('/OmSalesOrder/UpdateAuditorComment', {
                        Id: getOrderIdFromUrl(), // 大写I，与后端Auditor类的Id属性匹配
                        OrderStatus: newStatus, // 大写O
                        AuditorComment: auditOpinion.value, // 大写A
                        AuditorBy: usersId, // 大写A
                        AuditorTime: new Date().toISOString() // 大写A
                    });

                    if (response.data.code === 200) {
                        form.orderStatus = newStatus;
                        ElMessage.success('审核成功');
                        auditDialogVisible.value = false;

                        // 刷新页面数据
                        fetchOrderDetails();

                        // 联动管理页刷新
                        setTimeout(() => {
                            window.opener?.refreshTable();
                        }, 500);
                    } else {
                        ElMessage.error(response.data.msg || '审核失败');
                    }
                } catch (error) {
                    console.error('审核失败:', error);
                    ElMessage.error('审核失败，请重试');
                }
            };

            // 组件挂载时获取数据
            onMounted(() => {
                fetchOrderDetails();
            });

            return {
                form,
                orderStatusText,
                loading,
                activeTab,
                fileList,
                uploadedFiles,
                hoverIndex,
                handleUploadSuccess,
                handleUploadError,
                handleExceed,
                removeFile,
                printDialogVisible,
                printData,
                handlePrint,
                formatDate,
                handleEdit,
                handleDelete,
                handleCopy,
                handleEnableOrder,
                handleCloseOrder,
                handleRejectCancel,
                getStatusClass,
                auditDialogVisible,
                auditResult,
                auditOpinion,
                openAuditDialog,
                submitAudit,
            };
        }
    });

    // 注册Element Plus组件
    app.component('ElTabs', ElTabs);
    app.component('ElTabPane', ElTabPane);
    app.component('ElDialog', ElDialog);
    app.component('ElTable', ElTable);
    app.component('ElTableColumn', ElTableColumn);
    app.component('ElUpload', ElUpload);
    app.component('ElButton', ElButton);
    app.component('ElRadioGroup', ElRadioGroup);
    app.component('ElRadio', ElRadio);
    app.component('ElInput', ElInput);

    app.use(ElementPlus);
    app.mount('#app');
</script>
<style>
    /* 原有样式保持不变 */
    #app {
        margin-top: 20px;
        padding: 0 20px;
    }

    .form-label {
        display: inline-block;
        min-width: 80px;
        color: #606266;
    }

    .form-value {
        display: inline-block;
    }

    .basic-info {
        background-color: #fff;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        padding: 20px;
        margin-bottom: 20px;
        border-radius: 8px;
    }

    .tabs-container {
        background-color: #fff;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        min-height: 400px;
        padding: 20px;
        border-radius: 8px;
    }

    .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
    }

    .status-tag {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }

    .status-draft {
        background-color: #f0f0f0;
        color: #666;
    }

    .status-pending {
        background-color: #e6f7ff;
        color: #1890ff;
    }

    .status-rejected {
        background-color: #fff2f0;
        color: #ff4d4f;
    }

    .status-approved {
        background-color: #f6ffed;
        color: #52c41a;
    }

    .status-closed {
        background-color: #f5f5f5;
        color: #8c8c8c;
    }

    .stats-card {
        text-align: center;
        margin: 0 40px;
        padding: 15px;
        border-radius: 8px;
        background-color: #f8f9fa;
        min-width: 150px;
    }

    .stats-value {
        font-size: 20px;
        font-weight: bold;
        color: #409eff;
    }
</style>
